import React, {useState,useEffect} from "react";
import {map, trim} from "lodash";
import {Modal, Form, Input, Checkbox, Row, Col } from "antd/lib";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {policy} from "@/services/policy";
import {useQueryEnumsItems} from "@/services/enums";
import {UserProfile} from "@/components/proptypes";
import OrgUnit from "@/services/orgunit";
import notification from "@/services/notification";

function CreateOrgUnitDialog({ orgunit_id, dialog }) {
  const {optionsLoaded, options } = useQueryEnumsItems('orgunit_enum');
  const [dataLoaded, setDataLoaded] = useState(orgunit_id ===0 ? true : false);
  const [code, setCode] = useState("");
  const [name, setName] = useState("");
  const [shortname, setshortname] = useState("");
  const [orgUnitEnums, setOrgUnitEnums] = useState([]);
  const [isValid, setIsValid] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const isCreateOrgUnitEnabled =useState(true);// policy.isAdmin() || policy.isDefault();

  useEffect(() => {
    if (orgunit_id === 0) return;

    let cancelLoading = false;
    OrgUnit.get(orgunit_id).then(data => {
      if (!cancelLoading) {
        setCode(data.code);
        setName(data.name);
        setshortname(data.shortname);
        setOrgUnitEnums(data.orgunit_enums);
        setDataLoaded(true);
    }});

    return () => {
      cancelLoading = true;
    };
  }, [orgunit_id]);

  function handleCodeChange(event) {
    const value = trim(event.target.value);
    setCode(value);
    setIsValid(value !== "" && name !== "" && orgUnitEnums.length !== 0);
  }

  function handleNameChange(event) {
    const value = trim(event.target.value);
    setName(value);
    setIsValid(value !== "" && code !== "" && orgUnitEnums.length !== 0);
  }
  function handleshortNameChange(event) {
    const value = trim(event.target.value);
    setshortname(value);
    setIsValid(name !== "" && code !== "" && orgUnitEnums.length !== 0);
  }
  function handleOrgUnitEnumsChange(checkedValues) {
    setOrgUnitEnums(checkedValues);
    setIsValid(code !=="" && name !== "" && checkedValues.length !== 0);
  }

  function handleSubmit() {
    setSaveInProgress(true);

    if (orgunit_id === 0) {
      OrgUnit.create({code: code, name: name,shortname: shortname, orgunit_enums: orgUnitEnums})
        .then(() => {
          dialog.close({ success: true});
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
          setSaveInProgress(false);
        });
    } else {
      OrgUnit.save({id: orgunit_id, code: code, name: name,shortname: shortname, orgunit_enums: orgUnitEnums})
        .then(() => {
          dialog.close({ success: true});
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
          setSaveInProgress(false);
        });
    }
  }

  return (
    <Modal
      {...dialog.props}
      {...(isCreateOrgUnitEnabled ? {} : { footer: null })}
      title="部门"
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled: !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={handleSubmit}
      closable={!saveInProgress}
      maskClosable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      {dataLoaded && (
      <DynamicComponent name="CreateOrgUnitDialogExtra" disabled={!isCreateOrgUnitEnabled}>
      <Form>
        <Form.Item style={{ marginBottom: 5 }} label="单元代码">
        <Input
          defaultValue={code}
          onChange={handleCodeChange}
          placeholder="单元代码"
          disabled={saveInProgress}
          autoFocus
        />
        </Form.Item>
        <Form.Item style={{ marginBottom: 5 }} label="单元名称">
        <Input
          defaultValue={name}
          onChange={handleNameChange}
          placeholder="单元名称"
          disabled={saveInProgress}
        />
        </Form.Item>
        <Form.Item style={{ marginBottom: 5 }} label="简称">
        <Input
          value={shortname}
          onChange={handleshortNameChange}
          placeholder="简称"
          disabled={saveInProgress}
        />
        </Form.Item>
        {optionsLoaded && (
        <Form.Item style={{ marginBottom: 5 }} label="所属类型">
        <Checkbox.Group
          loading={!optionsLoaded}
          defaultValue={orgUnitEnums}
          onChange={handleOrgUnitEnumsChange}>
          <Row>
          {map(options, ds => (
            <Col span={8}><Checkbox value={ds.value}>{ds.title}</Checkbox></Col>
          ))}
          </Row>
        </Checkbox.Group>
        </Form.Item>
        )}
      </Form>
      </DynamicComponent>
      )}
    </Modal>
  );
}

CreateOrgUnitDialog.propTypes = {
  orgunit_id: UserProfile.isRequired,
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateOrgUnitDialog);
